package com.unswift.cloud.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.unswift.annotation.api.Api;
import com.unswift.annotation.api.ApiField;
import com.unswift.annotation.api.ApiMethod;
import com.unswift.cloud.core.CommonOperator;
import com.unswift.cloud.pojo.vo.page.PageVo;
import com.unswift.utils.ExceptionUtils;
import com.unswift.utils.ObjectUtils;

public abstract class BaseService extends CommonOperator{

	@ApiMethod(value="翻译数据", params = {@ApiField("分页对象"), @ApiField("翻译处理")})
	public <E> void translate(PageVo<E> page, DataTranslate<E> translateHandle) {
		ExceptionUtils.empty(translateHandle, "field.empty", "翻译处理对象");
		List<E> dataList=page.getDataList();
		if(ObjectUtils.isNotEmpty(dataList)) {
			translateHandle.init(dataList);
			for (E entity : dataList) {
				translateHandle.translate(entity);
			}
		}
	}
	
	@Api(value="数据翻译")
	public static abstract class DataTranslate<E> {
		
		@ApiField("临时缓存")
		private Map<String, Object> tempCache;
		
		@ApiMethod(value="缓存初始化，由开发者实现")
		public abstract void init(List<E> dataList);
		
		@ApiMethod(value="翻译逻辑，由开发者实现")
		public abstract void translate(E entity);
		
		@ApiMethod(value="设置缓存", params = {@ApiField("缓存的键"), @ApiField("缓存的值")})
		public void setCache(String key, Object value) {
			if(ObjectUtils.isNull(tempCache)) {
				tempCache=new HashMap<String, Object>();
			}
			tempCache.put(key, value);
		}
		
		@SuppressWarnings("unchecked")
		@ApiMethod(value="获取缓存", params = @ApiField("缓存的键"))
		public <V> V getCache(String key) {
			if(ObjectUtils.isNull(tempCache)) {
				return null;
			}
			return (V)tempCache.get(key);
		}
		
		@ApiMethod(value="缓存key是否存在", params = @ApiField("缓存的键"))
		public boolean existsCache(String key) {
			if(ObjectUtils.isNull(tempCache)) {
				return false;
			}
			return tempCache.containsKey(key);
		}
		
		@SuppressWarnings("unchecked")
		@ApiMethod(value="获取缓存是map的具体值")
		public <V> V getMapCache(String key, Object hashKey) {
			Map<?, ?> map=getCache(key);
			if(ObjectUtils.isNotEmpty(map)) {
				return (V)map.get(hashKey);
			}
			return null;
		}
	}
}
